package com.ulwx.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;



public class AccessFilter implements Filter {

	private static Logger log = Logger.getLogger(AccessFilter.class);
	protected FilterConfig filterConfig;
	private String loginPage;

	public void init(FilterConfig config) throws ServletException {
		this.filterConfig = config;
		loginPage = config.getInitParameter("loginPage");

		if (loginPage == null) {
			log.error("loginPage init param missing!");
			// throw new ServletException("loginPage init param missing");
		}
	}

	public void doFilter(final ServletRequest req, final ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest hreq = (HttpServletRequest) req;
		HttpServletResponse hres = (HttpServletResponse) res;
		Object user=  hreq.getSession().getAttribute("user");
		String context = hreq.getContextPath();
		log.debug("context="+context);
		if ( user != null  ) { // 检查是否登录
			chain.doFilter(req, res);
			return;
		} else{

			hres.sendRedirect(context+loginPage);
		}

	}

	public void destroy() {
		this.filterConfig = null;
	}

	public void setFilterConfig(final FilterConfig filterConfig) {
		this.filterConfig = filterConfig;
	}
}
